package com.huoxingy.print;

import com.huoxingy.print.domain.SalesFact;
import com.huoxingy.print.repo.SalesFactRepo;
import com.huoxingy.print.repo.SalesItemFactRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by hanxi on 2017/12/25.
 */
@Component
@Slf4j
public class OrderMessageHandler {
    private SalesFactJsonParser parser;
    private SalesFactRepo salesFactRepo;
    private SalesItemFactRepo salesItemFactRepo;

    @Autowired
    public OrderMessageHandler(SalesFactJsonParser parser, SalesFactRepo salesFactRepo, SalesItemFactRepo salesItemFactRepo) {
        this.parser = parser;
        this.salesFactRepo = salesFactRepo;
        this.salesItemFactRepo = salesItemFactRepo;
    }

    /**
     * @param json   订单信息
     * @param msgId  消息队列消息id
     * @param msgKey 消息队列消息key
     * @return 是否需要重试
     */
    public boolean process(String json, String msgId, String msgKey, int reconsumeTimes) {
        this.parser.parse(json);

        SalesFact salesFact = this.parser.getSalesFact();
        if (null != salesFact) {
            if (null == this.salesFactRepo.findOne(salesFact.getId())) {
                this.salesFactRepo.save(salesFact);
                if (null != this.parser.getItems()) {
                    this.salesItemFactRepo.save(this.parser.getItems());
                }
            } else {
                log.info("Sales order:{} saved before, just ignore it...", salesFact.getId());
            }
        }
        return true;
    }

}
